package djboom.materials.display.page.work3 {
	import djboom.materials.events.CupEvent;
	import djboom.materials.Work;
	import djboom.materials.core.BitmapDataCore;
	import djboom.materials.core.DataCore;
	import djboom.materials.display.devices.BottleOfWater;
	import djboom.materials.display.devices.Cup;
	import djboom.materials.display.devices.Desiccator;
	import djboom.materials.display.devices.FlaskLeChatelier;
	import djboom.materials.display.devices.Scales;
	import djboom.materials.display.elements.Instruction;
	import djboom.materials.display.elements.TableData;
	import djboom.materials.display.elements.TableDataCell;
	import djboom.materials.display.elements.Window;
	import djboom.materials.display.page.Navigation;
	import djboom.materials.display.page.Page;
	import djboom.materials.events.BottleOfWaterEvent;
	import djboom.materials.events.DesiccatorEvent;
	import djboom.materials.events.InstructionEvent;
	import djboom.materials.events.PageEvent;
	import djboom.materials.events.TableDataCellEvent;
	import djboom.materials.events.WindowEvent;

	import com.greensock.TweenLite;
	import com.greensock.easing.Cubic;

	import org.casalib.display.CasaTextField;
	import org.casalib.util.FrameUtil;
	import org.casalib.util.NumberUtil;
	import org.casalib.util.StageReference;

	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	/**
	 * .
	 * <br>
	 * 
	 * @author DJ BooM 
	 * @since 28.04.2010
	 * 
	 */

	public class Page4 extends Page {

		// ----------------------------------------------------------------------------
		// Константы класса.
		// ----------------------------------------------------------------------------

		private static const OPEN_WATER_CLIP:String = "work3.OpenWaterClip";

		// ----------------------------------------------------------------------------
		// Свойства класса.
		// ----------------------------------------------------------------------------

		private var _materialsList:XMLList;

		private var _sampleMaterialXML:XML;

		private var _tableDataXML:XML;

		private var _instruction:Instruction;

		private var _tableData:TableData;
		private var _window:Window;

		private var _helpField:CasaTextField;
		private var _bottleOfWater:BottleOfWater;
		private var _flaskLeChatelier:FlaskLeChatelier;
		private var _cup:Cup;
		private var _desiccator:Desiccator;
		private var _scales:Scales;
		private var _openWaterClip:MovieClip;
		private var _weightCupPowder:String;
		private var _absoluteAmountSample:String;
		private var _weightCupRestPowder:String;

		// ----------------------------------------------------------------------------
		// Конструктор.
		// ----------------------------------------------------------------------------

		public function Page4() {
			super();
		}	 

		// ----------------------------------------------------------------------------
		// Методы класса.
		// ----------------------------------------------------------------------------

		override public function init():void {
			// Создаем заголовок страницы.
			createTitleWork(Page.WORK3_NAME, 3);
            
			// Создаем инструкцию.
			_instruction = new Instruction(DataCore.INSTRUCTION_WORK_3.child("instruction"));
			_instruction.addEventListener(InstructionEvent.LIGHT_CELL, lightTableCell);
			_instruction.addEventListener(InstructionEvent.AUTO, applyAuto);
			addChild(_instruction);
            
			_materialsList = DataCore._materialsWork3XML.child("material").(@select == "true");
            
			createTableDataXML();
            
			_tableData = new TableData(BitmapDataCore.getBitmapData(BitmapDataCore.WORK3_TABLEDATA), _tableDataXML, new Point(16, 108), TableDataCell.CELL_FORMAT_19PX);
			_tableData.x = 20;
			_tableData.y = 82 + _instruction.scrollHeight;
			_tableData.addEventListener(TableDataCellEvent.INPUT_ERROR, inputError);
			_tableData.addEventListener(TableDataCellEvent.INPUT_SUCCESS, inputSuccess);
			_tableData.addEventListener(TableDataCellEvent.INPUT_LAST_CELL, inputLastCell);
            
            
			_tableData.scrollRect = new Rectangle(0, _tableData.height, _tableData.width, 0);
			addChild(_tableData);
            
			_sampleMaterialXML = _materialsList[0] as XML;
			
			_scales = new Scales("0.00", "ПРЕДЕЛЬНАЯ НАГРУЗКА 1000 г");
			_scales.x = 715;
			_scales.y = 554;
			addChild(_scales);
			
			_bottleOfWater = new BottleOfWater();
			_bottleOfWater.x = 3;			_bottleOfWater.y = 183;
			_bottleOfWater.addEventListener(BottleOfWaterEvent.OPEN_WATER, openWater);			addChild(_bottleOfWater);
			
			
			_desiccator = new Desiccator(_sampleMaterialXML.attribute("name").toString());
			_desiccator.x = 513;
			_desiccator.y = 645;
			_desiccator.addEventListener(InstructionEvent.REFRESH, refreshInstruction);			_desiccator.addEventListener(DesiccatorEvent.SPOON_1, desiccatorSpoon1);			_desiccator.addEventListener(DesiccatorEvent.SPOON_2, desiccatorSpoon2);
						addChild(_desiccator);			
			_cup = new Cup();
			_cup.x = 817;
			_cup.y = 525;
			_cup.addEventListener(InstructionEvent.REFRESH, refreshInstruction);
			_cup.addEventListener(CupEvent.ANIMATE_WATER, animateCupWater);			addChild(_cup);
			
			_flaskLeChatelier = new FlaskLeChatelier();
			_flaskLeChatelier.x = 353;			_flaskLeChatelier.y = 413;
			_flaskLeChatelier.absoluteAmountSample = Number(_absoluteAmountSample);
			addChild(_flaskLeChatelier);
			
			/**
			 * Установите прибор Ле-Шателье под краном склянки с дистиллированной водой.
			 * Даём возможность перетаскивания прибора.
			 * 
			 */

			_flaskLeChatelier.addEventListener(MouseEvent.MOUSE_DOWN, setupDragFlask);
			_flaskLeChatelier.addEventListener(MouseEvent.MOUSE_UP, stopDragFlask);
		}
		
		
		private function createTableDataXML():void {
			_tableDataXML = <tabledata></tabledata>;
            
			for each (var materialXML:XML in _materialsList) {
				var materialName:String = materialXML.attribute("name").toString();
				var weightCupPowder:String = materialXML.attribute("weightCupPowder").toString();				var weightCupRestPowder:String = materialXML.attribute("weightCupRestPowder").toString();				var weightSample:String = materialXML.attribute("weightSample").toString();				var absoluteAmountSample:String = materialXML.attribute("absoluteAmountSample").toString();				var trueDenSityG:String = materialXML.attribute("trueDenSityG").toString();				var trueDenSityKG:String = materialXML.attribute("trueDenSityKG").toString();
				
				_weightCupPowder = weightCupPowder;
				_weightCupRestPowder = weightCupRestPowder;
				_absoluteAmountSample = absoluteAmountSample;
				
				_tableDataXML.appendChild(<row>
                    <cell align="left" width="259">
                      <data>{materialName}</data>
                    </cell>
                    <cell align="center" width="130">
                      <data> </data>
                      <checkData>{weightCupPowder}</checkData>
                    </cell>
                    <cell align="center" width="128">
                      <data> </data>
                      <checkData>{weightCupRestPowder}</checkData>
                    </cell>
                    <cell align="center" width="107">
                      <data> </data>
                      <checkData>{weightSample}</checkData>
                    </cell>
                    <cell align="center" width="109">
                      <data> </data>
                      <checkData>{absoluteAmountSample}</checkData>
                    </cell>
                    <cell align="center" width="104">
                      <data> </data>
                      <checkData>{trueDenSityG}</checkData>
                    </cell>
                    <cell align="center" width="106">
                      <data> </data>
                      <checkData>{trueDenSityKG}</checkData>
                    </cell>
                </row>);
			}
		}

		
		
		private function lightTableCell(event:InstructionEvent):void {
			_tableData.y = 82 + _instruction.scrollHeight;
			_tableData.enableCell(0 + event.cellName);
			
			TweenLite.to(_tableData, 0.5, {scrollRect: {x: 0, y: 0, width: _tableData.width, height: _tableData.scrollHeight}, ease: Cubic.easeInOut, delay: 1});
		}

		private function inputError(event:TableDataCellEvent):void {
			lockPage();
            
			_window = new Window();
			_window.addEventListener(WindowEvent.CLOSE, repeatEnableCell);
			_window.init("Внимание!", "Введены некорректные данные");
			addChild(_window);
		}

		private function repeatEnableCell(event:WindowEvent):void {
			unlockPage();
            
			if (_window != null) {
				_window.destroy();
				_window = null;
			}
            
			_tableData.repeatEnableCell();
		}

		private function inputSuccess(event:TableDataCellEvent):void {
			var inputCell:Boolean = _instruction.checkInputCell();
			
			if (!inputCell) TweenLite.to(_tableData, 0.5, {scrollRect: {x: 0, y: _tableData.scrollHeight, width: _tableData.width, height: 0}, ease: Cubic.easeInOut});
            
			_instruction.nextInstruction();
			
			switch(_instruction.instructionID) {
				case 5:
					//					_helpField.destroy();
					//					_helpField = null;

					break;
			}
		}

		private function inputLastCell(event:TableDataCellEvent):void {
			lockPage();
            
			_window = new Window();
            
			Navigation.toggleEnabled(Page.WORK_3_PAGE_1, false);
            
			_window.addEventListener(WindowEvent.CLOSE, navigationPage);
			_window.init("Поздравляем!", "Вы успешно справились с работой №3. Перейдите к заключению.");
			addChild(_window);
		}

		private function navigationPage(event:WindowEvent):void {
			var pageEvent:PageEvent = new PageEvent(PageEvent.CHANGE);
			pageEvent.pageName = Page.CONCLUSION;            
			dispatchEvent(pageEvent);
		}

		
		/**
		 * Обновляем инструкции к работе.
		 * 
		 */

		private function refreshInstruction(event:InstructionEvent):void {
			_instruction.nextInstruction();
			
			
			switch(_instruction.instructionID) {
				case 6:

					_scales.animateWeightDownRelative(10);
					_scales.setupWeight(String(_weightCupRestPowder));
            
					TweenLite.to(_cup, 0.5, {y: "10", ease: Cubic.easeOut});

					break;
			}
		}

		
		private function setupDragFlask(event:MouseEvent):void {
			_flaskLeChatelier.startDrag(false, new Rectangle(3, 413, Work.WIDTH - 6 - _flaskLeChatelier.width, 0));
            
			StageReference.getStage().addEventListener(MouseEvent.MOUSE_UP, captureMouseUp);
		}

		private function stopDragFlask(event:MouseEvent = null):void {
			_flaskLeChatelier.stopDrag();
            
			StageReference.getStage().removeEventListener(MouseEvent.MOUSE_UP, captureMouseUp);
            
			if (_flaskLeChatelier.x >= 156 && _flaskLeChatelier.x <= 168 ) {
				_flaskLeChatelier.removeEventListener(MouseEvent.MOUSE_DOWN, setupDragFlask);
				_flaskLeChatelier.removeEventListener(MouseEvent.MOUSE_UP, stopDragFlask);
                        
				TweenLite.to(_flaskLeChatelier, 0.4, {x: 162, ease: Cubic.easeIn});
                
				_instruction.nextInstruction();
				
				
				_bottleOfWater.enable();
			} else {
				TweenLite.to(_flaskLeChatelier, 0.6, {x: 353, ease: Cubic.easeOut});
			}
		}

		
		/**
		 * Реализация функции ReleaseOutside.
		 * 
		 */

		private function captureMouseUp(event:MouseEvent):void {
			if (event.target == _flaskLeChatelier || _flaskLeChatelier.contains(DisplayObject(event.target))) {
			} else {
				stopDragFlask();
			}
		}

		private function openWater(event:BottleOfWaterEvent):void {
			_flaskLeChatelier.filledWater();
			
			_openWaterClip = BitmapDataCore.getMovieClip(OPEN_WATER_CLIP);
			_openWaterClip.x = 194;			_openWaterClip.y = 319;
			addChild(_openWaterClip);
			
			FrameUtil.addFrameScript(_openWaterClip, BitmapDataCore.LABEL_COMPLETE, removeWaterClip); 
		}

		private function removeWaterClip():void {
			FrameUtil.removeFrameScript(_openWaterClip, BitmapDataCore.LABEL_COMPLETE);
			
			_openWaterClip.stop();
			_openWaterClip.visible = false;
			removeChild(_openWaterClip);
			_openWaterClip = null;
			
			TweenLite.to(_flaskLeChatelier, 1, {x: 262, ease: Cubic.easeInOut, onComplete: closeWaterComplete});
		}

		private function closeWaterComplete():void {
			_instruction.nextInstruction();
			
			TweenLite.to(_bottleOfWater, 1, {alpha: 0});
		}

		
		public function AutoAction1():void {
			_desiccator.animate();
		}

		private function desiccatorSpoon1(event:DesiccatorEvent):void {
			_scales.animateWeightDownRelative(5);
			_scales.setupWeight(String(NumberUtil.roundDecimalToPlace(Number(_weightCupPowder) / 2, 2)));
			
			
			TweenLite.to(_cup, 0.5, {y: "5", ease: Cubic.easeOut});
		}

		private function desiccatorSpoon2(event:DesiccatorEvent):void {
			_scales.animateWeightDownRelative(5);
			_scales.setupWeight(_weightCupPowder);
        	
			TweenLite.to(_cup, 0.5, {y: "5", ease: Cubic.easeOut});
		}

		public function AutoAction2():void {
			_scales.clearScale();
        	
			_cup.animate();
		}

		private function animateCupWater(event:CupEvent):void {
			_flaskLeChatelier.animateWater();
		}

		
		// ----------------------------------------------------------------------------
		// Публичные методы.
		// ----------------------------------------------------------------------------

		/**
		 * Очистка страницы.
		 * 
		 */

		override protected function clearPage(event:Event):void {
			super.clearPage(event);
			
			_materialsList = null;
			
			_sampleMaterialXML = null;
			_tableDataXML = null;
			
			_tableData.destroy();
			_tableData = null;
			
			_instruction.destroy();
			_instruction = null;
			
			if (_window != null) {
				_window.destroy();
				_window = null;
			}
			
			if (_helpField != null) {
				_helpField.destroy();
				_helpField = null;
			}
		}
        
		// ----------------------------------------------------------------------------
        // Публичные свойства.
        // ----------------------------------------------------------------------------
	}
}
